var util = require('util'),
    http = require('http'),
    fs = require('fs'),
    path = require('path'),
    querystring = require('querystring');
    
// Costum module
var config = require('./config').config;
var handle = require('./requestHandler').handle;
var login = require('./control/login').login;

// global var
var dateTime = new Date();
var errMsg = "";
// Get the mime type of file
var mime = config.mime;
var ext = "";

function staticView(req, res, filename, ext) {
  // Set the path of file
  var fileRealPath = path.join('view', path.normalize(filename.replace(/\.\./g, '')));

  var contentType = mime[ext] || "text/plain";
  
  path.exists(fileRealPath, function(exists) {
    if(!exists) {
      res.writeHead(404, {"Content-Type": contentType});
      res.write("404 Not Found\n");
      errMsg = "404: " + filename + " Does Not Found.";
      console.log(dateTime + ' │ ' + filename + ' ' + errMsg);
      res.end();
      return;
    }
    fs.readFile(fileRealPath, 'utf-8', function(err, content) {
      if(err) {
        res.writeHead(500, {"Content-Type": contentType});
        res.write("500 Not Exist\n");
        errMsg = "500: " + filename + " Does Not Exist.";
        console.log(dateTime + ' │ ' + filename + ' ' + errMsg);
        res.end();
        return;
      } else {
        res.writeHead(200, {"Content-Type": contentType, 
                            "Access-Control-Allow-Origin": "*"});
        res.write(content);
        res.end();
      }
    });
    console.log(dateTime + ' │ ' + filename);
  });
}

function dynamicView(req, res, path, postData) {
  // path
  switch(path) {
    case '/login':
      username = querystring.parse(postData).username;
      password = querystring.parse(postData).password;
      
      res.writeHead(200, {"Content-Type": "text/html", 
                          "Access-Control-Allow-Origin": "*"});
      res.write(login(username, password));
      res.end();
      break;
    default:
      res.writeHead(404, {"Content-Type": "text/plain"});
      res.write("404 Not Found\n");
      errMsg = "404: " + path + " Does Not found.";
      res.end();
      console.log(dateTime + ' │ ' + path + ' ' + errMsg);
      return;
  }
  // queryStrings
  console.log(dateTime + ' │ ' + path);
}

function view(req, res, pathname, postData) {
  var ext = path.extname(pathname);
  ext = ext ? ext.slice(1) : "";
  if(ext === "") {
    dynamicView(req, res, pathname, postData);
  } else {
    staticView(req, res, pathname, ext);
  }
}

exports.view = view;